package org.tinygroup.template.interpret.context;

import java.io.Writer;
import java.util.List;

import org.tinygroup.template.TemplateContext;
import org.tinygroup.template.interpret.ContextProcessor;
import org.tinygroup.template.interpret.TemplateFromContext;
import org.tinygroup.template.interpret.TemplateInterpretEngine;
import org.tinygroup.template.interpret.TemplateInterpreter;
import org.tinygroup.template.parser.grammer.TinyTemplateParser;
import org.tinygroup.template.rumtime.TemplateMap;

/**
 * Created by luog on 15/7/17.
 */
public class MapProcessor implements ContextProcessor<TinyTemplateParser.Expr_hash_mapContext> {


  public Class<TinyTemplateParser.Expr_hash_mapContext> getType() {
    return TinyTemplateParser.Expr_hash_mapContext.class;
  }

  public boolean processChildren() {
    return false;
  }

  @SuppressWarnings("unchecked")
  public Object process(TemplateInterpreter interpreter, TemplateFromContext templateFromContext,
      TinyTemplateParser.Expr_hash_mapContext parseTree, TemplateContext context, Writer writer,
      TemplateInterpretEngine engine) throws Exception {
    List<TinyTemplateParser.ExpressionContext> expressions =
        parseTree.hash_map_entry_list().expression();
    TemplateMap tmap = new TemplateMap();
    if (expressions != null) {
      for (int i = 0; i < expressions.size(); i += 2) {
        String key = interpreter
            .interpretTree(engine, templateFromContext, expressions.get(i), context, writer)
            .toString();
        String value = interpreter
            .interpretTree(engine, templateFromContext, expressions.get(i + 1), context, writer)
            .toString();
        tmap.put(key, value);
        tmap.getBlockingDeque().add(key);
        tmap.getBlockingDeque().add(value);
      }
    }
    return tmap;
  }

}

